#!/bin/bash

# DESC: Walkforward simulation. 

# USAGE: source walkforward.parallel.sc nP data_labels_file data_in_file data_out_file walkforward_dat_file run_script postproc_script
#
#     nP
#     data_labels_file
#     data_in_file
#     data_out_file
#     walkforward_dat_file
#     run_script
#     postproc_script

#=========================================================

# =====
# PARAMETERS
# =====

# NOTE: These are all read from the command line.

nP=$1
data_labels_file=$2
data_in_file=$3
data_out_file=$4
walkforward_dat_file=$5
run_script=$6
postproc_script=$7

#=========================================================

wfrs="walkforward_run_script.txt"

#=========================================================

# =====
# WALKFORWARD
# =====

cnt=0

pcnt=0

# READ EACH LINE OF WALKFORWARD FILE
while read -r line; do

    let cnt=$cnt+1

    # SETUP WALKFORWARD DIRECTORY
    dir_name=$cnt
    rm -r $dir_name
    mkdir $dir_name

    # READ WALKFORWARD RANGE(S) FOR THIS LINE
    tr_s=$(echo $line | cut -d " " -f 1)
    tr_e=$(echo $line | cut -d " " -f 2)
    te_s=$(echo $line | cut -d " " -f 3)
    te_e=$(echo $line | cut -d " " -f 4)
    echo $tr_s $tr_e $te_s $te_e

    # CREATE TRAINING AND TESTING FILES
    $(sed -n "$tr_s","$tr_e"p $data_labels_file > $dir_name/train_$data_labels_file)
    $(sed -n "$tr_s","$tr_e"p $data_in_file > $dir_name/train_$data_in_file)
    $(sed -n "$tr_s","$tr_e"p $data_out_file > $dir_name/train_$data_out_file)

    $(sed -n "$te_s","$te_e"p $data_labels_file > $dir_name/test_$data_labels_file)
    $(sed -n "$te_s","$te_e"p $data_in_file > $dir_name/test_$data_in_file)
    $(sed -n "$te_s","$te_e"p $data_out_file > $dir_name/test_$data_out_file)

    # COPY RUN SCRIPT
    $(cp $run_script $dir_name/)

    # WRITE RUN INFORMATION TO RUN SCRIPT
    let pcnt=$pcnt+1

    echo "cd $dir_name" >> $wfrs
    echo "source $run_script &" >> $wfrs
    echo "cd ../" >> $wfrs

    if [ "$pcnt" -eq "$nP" ]; then
        echo "wait" >> $wfrs

        let pcnt=0
    fi

done < "$walkforward_dat_file"

$(source $wfrs)

$(source $postproc_script $cnt)
